import { _decorator, Component, Node } from 'cc';
import I18n, { CountryType, LangType } from '../i18n/I18n';
import { ClientAPI } from '../src/api/client.api';
import ServiceAPI from '../src/api/service.api';
import GlobalData from './GlobalData';
import { Loading } from './Loading';
import { LocalStorageMgr } from './LocalStorageMgr';
const { ccclass, property } = _decorator;

const COUNTRY_LIST = ['US', "JP", "BR", "KR", "DE", "FR", "GB", "US", "CA", "AU"];

const DEFAULT_LOCAL = {
    countryCode: 'US',
    languageCode: 'en'
}

@ccclass('InitData')
export class InitData extends Component {

    @property(Loading)
    loading: Loading = null;
    @property(Node)
    bg: Node = null;

    async onLoad() {
        mtec.cc.adaptBackgroundNode(this.bg);
        await this.initUserData();

        I18n.init(GlobalData.language as LangType, GlobalData.country as CountryType);
    }

    async initUserData() {
        //  userId
        let uid = LocalStorageMgr.getItem(LocalStorageMgr.userId_key) //this.getOrSetLocalData(LocalStorageMgr.userId_key, GlobalData.userId);
        let isnew = LocalStorageMgr.getItem(LocalStorageMgr.isCommer_key)//
        console.log('是否已经有用户id，是否是新手：', uid, isnew);
        console.log(!uid, !GlobalData.userId, isnew);

        //  初始化用户
        if (!uid || isnew) {
            LocalStorageMgr.clear();
            console.log("初始化用户");

            let [local, device_id] = await Promise.all([ClientAPI.Local(), ClientAPI.DeviceID().then(res => res.device_id)]);
            GlobalData.deviceId = device_id;
            LocalStorageMgr.setItem(LocalStorageMgr.device_id_key, GlobalData.deviceId);
            if (!COUNTRY_LIST.includes(local.countryCode)) {
                local = DEFAULT_LOCAL;
            }

            await GlobalData.fetchAndUpdateData('initUser', () => ServiceAPI.initUser(device_id, local.countryCode));

            GlobalData.userId = GlobalData.getDataStore().initUser.userId;
            LocalStorageMgr.setItem(LocalStorageMgr.userId_key, GlobalData.userId);

            LocalStorageMgr.setItem(LocalStorageMgr.country_key, GlobalData.getDataStore().initUser.country);
            LocalStorageMgr.setItem(LocalStorageMgr.language_key, GlobalData.getDataStore().initUser.language);
        }
        GlobalData.userId = LocalStorageMgr.getItem(LocalStorageMgr.userId_key)
        await GlobalData.fetchAndUpdateData('userInfo', () => ServiceAPI.userInfo(GlobalData.userId));
        await GlobalData.fetchAndUpdateData('ConfCommon', () => ServiceAPI.ConfCommon(GlobalData.userId));
        await GlobalData.fetchAndUpdateData('WithdrawConfig', () => ServiceAPI.WithdrawConfig(GlobalData.userId));

        GlobalData.country = GlobalData.getDataStore().userInfo.country;
        GlobalData.language = GlobalData.getDataStore().userInfo.language;


        // 更新钱数
        GlobalData.curCashTotal = GlobalData.getDataStore().userInfo.cashTotal;
        // 更新红包数
        GlobalData.redPacket = GlobalData.getDataStore().userInfo.redPacket;

        // 获取地区配置
        await GlobalData.fetchAndUpdateData('ConfCountry', () => ServiceAPI.ConfCountry(GlobalData.country));

        //  强弹间隔
        GlobalData.luckyWardPageInterval = GlobalData.getDataStore().ConfCommon.popEliminateCount;
        //  任务配置
        GlobalData.missionData = GlobalData.getDataStore().ConfCommon.missionConfig;
        // console.log(GlobalData.missionData);

        GlobalData.isWDNewWard = this.getOrSetLocalData(LocalStorageMgr.isWDNewWard_key, GlobalData.isWDNewWard);

        // 获取普通领取红包的次数
        GlobalData.luckyWardNorgetTimes = this.getOrSetLocalData(LocalStorageMgr.luckyWardNorgetTimes_key, GlobalData.luckyWardNorgetTimes)

        //  获取道具个数
        GlobalData.refrashPropNum = this.getOrSetLocalData(LocalStorageMgr.refrashPropNum_key, GlobalData.refrashPropNum);
        GlobalData.hummerPropNum = this.getOrSetLocalData(LocalStorageMgr.hummerPropNum_key, GlobalData.hummerPropNum)
        //  分数记录
        GlobalData.curScore = this.getOrSetLocalData(LocalStorageMgr.curScore_key, GlobalData.curScore);
        GlobalData.historyHighScore = this.getOrSetLocalData(LocalStorageMgr.historyHighScore_key, GlobalData.historyHighScore);
        GlobalData.todayHighScore = this.getOrSetLocalData(LocalStorageMgr.todayHighScore_key, GlobalData.todayHighScore);
        // console.log(GlobalData.curScore, GlobalData.historyHighScore, GlobalData.todayHighScore);


        //  是否新手
        GlobalData.isCommer = this.getOrSetLocalData(LocalStorageMgr.isCommer_key, GlobalData.isCommer);
        console.log("是否是新手", GlobalData.isCommer);
        GlobalData.deviceId = LocalStorageMgr.getItem(LocalStorageMgr.device_id_key)

        //  引导记录
        GlobalData.guideRecord = this.getOrSetLocalData(LocalStorageMgr.guideRecord_key, GlobalData.guideRecord);
        // if (GlobalData.isCommer && GlobalData.guideRecord < 10) {
        //     LocalStorageMgr.setItem(LocalStorageMgr.guideRecord_key, 1);
        //     GlobalData.guideRecord = this.getOrSetLocalData(LocalStorageMgr.guideRecord_key, GlobalData.guideRecord);
        //     LocalStorageMgr.setItem(LocalStorageMgr.elimiTimes_key, 0);
        // }

        GlobalData.curlotteryTimes = this.getOrSetLocalData(LocalStorageMgr.curlotteryTimes_key, GlobalData.curlotteryTimes);
        //  消除次数-临时，用于lottery强弹
        GlobalData.tempElimiTimes_lottery = this.getOrSetLocalData(LocalStorageMgr.tempElimiTimes_lottery_key, GlobalData.tempElimiTimes_lottery);

        //  消除次数
        GlobalData.elimiTimes = this.getOrSetLocalData(LocalStorageMgr.elimiTimes_key, GlobalData.elimiTimes);
        //  消除次数-临时，用于lucky强弹
        GlobalData.tempElimiTimes_lucky = this.getOrSetLocalData(LocalStorageMgr.tempElimiTimes_lucky_key, GlobalData.tempElimiTimes_lucky);

        //  上次游戏保存的地图
        GlobalData.lastGameBoard = this.getOrSetLocalData(LocalStorageMgr.lastGameBoardData_key, GlobalData.lastGameBoard);

        //  获取上次登录时间
        GlobalData.lastLoginDate = this.getOrSetLocalData(LocalStorageMgr.lastLoginDate_key, GlobalData.lastLoginDate);


        //this.loading.loadScene('main'); // pure / main;

		ClientAPI.GameType().then(type=>this.loading.loadScene(type=='A'?'pure':'main'));
    }

    public getOrSetLocalData(storage_key: string, storage: any) {
        let ishave = LocalStorageMgr.hasItem(storage_key);
        if (!ishave) {
            LocalStorageMgr.setItem(storage_key, storage);
        }
        return LocalStorageMgr.getItem<typeof storage>(storage_key);
    }


    start() {

    }

    update(deltaTime: number) {

    }
}

